package com.itboye.ihomebank.activity.myzhujia.qianbao;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.itboye.ihomebank.R;
import com.itboye.ihomebank.util.alipay.OrderInfoUtil2_0;
import com.itboye.ihomebank.util.alipay.PayResult;
import com.itboye.ihomebank.base.BaseOtherActivity;
import com.itboye.ihomebank.bean.BindCardsList;
import com.itboye.ihomebank.bean.PayInfo;
import com.itboye.ihomebank.bean.ResultEntity;
import com.itboye.ihomebank.bean.RongFengsBean;
import com.itboye.ihomebank.constants.NetPublicConstant;
import com.itboye.ihomebank.constants.SPContants;
import com.itboye.ihomebank.activity.me.ActivityZhangHu;
import com.itboye.ihomebank.presenter.UserPresenter;
import com.itboye.ihomebank.util.ByAlert;
import com.itboye.ihomebank.util.CashierInputFilter;
import com.itboye.ihomebank.util.SPUtils;
import com.itboye.ihomebank.util.TimeFormat;
import com.itboye.ihomebank.util.WritePassPopupWindow;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog;
import com.itboye.ihomebank.util.WriteYanZhengMaDialog.OnfinishListener;
import com.itboye.ihomebank.web.WebActivity;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;

/**
 * 账户充值
 */
public class ActivityChongZhi extends BaseOtherActivity implements Observer,
        OnfinishListener {
    View v_statusbar;
    TextView add_shap_title_tv;
    ImageView close_icon;

    ImageView cb_zhifubao, cb_weixin, cb_yinhangka;

    EditText chongzhi_money;
    TextView chongzhi_ok;

    private Dialog dialog;// 自定义Dialog
    UserPresenter userPresenter;
    boolean isZFB = true;
    private String uid;
    private boolean yhk;
    private boolean wx,xiaotong;
    RelativeLayout choose_card;
    private String bankId;
    TextView bank_type, card_type, item_zhanghu_num;
    private WritePassPopupWindow passPopupWindow;
    private EditText pass;
    private String money;

    RongFengsBean rongFengBean;
    String order_no;//荣丰支付得到的num

    //平安支付
    private ImageView safety_selectBtn;
    private RelativeLayout choose_safetycard;
    private TextView bank_safetytype,card_safetytype,item_zhanghu_safetynum;
    private boolean safety;

    private RelativeLayout zhifu_pay,inner;
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.close_icon:
                finish();
                break;
            case R.id.chongzhi_ok:
                uid = SPUtils.get(this, null, SPContants.USER_ID, "") + "";
                money = chongzhi_money.getText().toString();
                if (money.equals("")) {
                    ByAlert.alert("请输入充值金额");
                    return;
                }

                if (safety){
                    DecimalFormat df = new DecimalFormat("#.00");// 保留两位小数
                    BigDecimal bg = new BigDecimal(Double.parseDouble(money) * 100);
                    String innermoney = df.format(bg);
                    userPresenter.payHouse(uid, "recharge", "", "6693", "", innermoney, "0");
                }else {
                    passPopupWindow = new WritePassPopupWindow(this, this);
                    pass = (EditText) passPopupWindow.getContentView()
                            .findViewById(R.id.pass);
                    passPopupWindow.setBackgroundDrawable(new BitmapDrawable());
                    passPopupWindow.setFocusable(true);
                    passPopupWindow.setSoftInputMode(PopupWindow.INPUT_METHOD_NEEDED);
                    passPopupWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                    passPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
                }

                break;
            case R.id.cb_zhifubao:
                isZFB = true;
                wx = false;
                yhk = false;
                xiaotong=false;
                safety=false;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.GONE);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                cb_zhifubao.setBackgroundResource(R.drawable.select);
                cb_weixin.setBackgroundResource(R.drawable.unselect);
                cb_yinhangka.setBackgroundResource(R.drawable.unselect);
                break;

            case R.id.safety_selectBtn:
                wx = false;
                isZFB = false;
                yhk = false;
                xiaotong=false;
                safety=true;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.VISIBLE);
                safety_selectBtn.setBackgroundResource(R.drawable.select);
                cb_weixin.setBackgroundResource(R.drawable.unselect);
                cb_zhifubao.setBackgroundResource(R.drawable.unselect);
                cb_yinhangka.setBackgroundResource(R.drawable.unselect);
                break;
            case R.id.cb_weixin:
                wx = true;
                isZFB = false;
                yhk = false;
                xiaotong=false;
                safety=false;
                choose_card.setVisibility(View.GONE);
                choose_safetycard.setVisibility(View.GONE);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                cb_weixin.setBackgroundResource(R.drawable.select);
                cb_zhifubao.setBackgroundResource(R.drawable.unselect);
                cb_yinhangka.setBackgroundResource(R.drawable.unselect);
                break;
            case R.id.cb_yinhangka:
                yhk = true;
                isZFB = false;
                wx = false;
                xiaotong=false;
                safety=false;
                choose_card.setVisibility(View.VISIBLE);
                choose_safetycard.setVisibility(View.GONE);
                safety_selectBtn.setBackgroundResource(R.drawable.unselect);
                cb_yinhangka.setBackgroundResource(R.drawable.select);
                cb_zhifubao.setBackgroundResource(R.drawable.unselect);
                cb_weixin.setBackgroundResource(R.drawable.unselect);
                break;

            case R.id.choose_card:
                Intent intent = new Intent(this, ActivityZhangHu.class);
                intent.putExtra("type", 1);
                startActivityForResult(intent, 101);
                break;
            case R.id.choose_safetycard:// 添加平安银行卡
                Intent intent1 = new Intent(this, ActivityZhangHu.class);
                intent1.putExtra("type", 1);
                startActivityForResult(intent1, 103);
                break;
            case R.id.ok:
                dialog.dismiss();
                break;
            case R.id.cancel:
                dialog.dismiss();
            case R.id.btn_ok:
                String password = pass.getText().toString();
                if (password.equals("")) {
                    ByAlert.alert("请输入余额支付密码");
                    return;
                }

                userPresenter.yueYanzheng(uid, password);
                passPopupWindow.dismiss();
                break;
            case R.id.btn_cancel:
                passPopupWindow.dismiss();
                break;
            default:
                break;
        }
    }


    @Override
    protected int layout_id() {
        return R.layout.activity_chong_zhi;
    }

    @Override
    protected void onInitController() {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onActivityResult(int arg0, int arg1, Intent arg2) {
        // TODO Auto-generated method stub
        super.onActivityResult(arg0, arg1, arg2);
        if (arg0 == 101 && arg1 == 102) {
            if (arg2 != null) {
                BindCardsList bindCardsList = (BindCardsList) arg2
                        .getSerializableExtra("model");
                //	bankId = bindCardsList.getBankNo();
                bankId = bindCardsList.getId();
                bank_type.setText(bindCardsList.getBank().get(0));
                card_type.setText(bindCardsList.getBank().get(1));

                String num = bindCardsList.getBankNo();//银行卡号
                if (num.length() > 4) {
                    String s = num.substring(num.length() - 4, num.length());//后四位
                    String ss = num.substring(0, num.length() - 4);//后四位
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < ss.length(); i++) {
                        sb.append("*");
                    }
                    item_zhanghu_num.setText(sb + s);
                } else {
                    item_zhanghu_num.setText(bindCardsList.getBankNo());
                }

            }
        }else if (arg0 == 103 && arg1 == 102){
            if (arg2 != null) {
                BindCardsList bindCardsList = (BindCardsList) arg2
                        .getSerializableExtra("model");
                //	bankId = bindCardsList.getBankNo();
                bankId = bindCardsList.getId();
                bank_safetytype.setText(bindCardsList.getBank().get(0));
                card_safetytype.setText(bindCardsList.getBank().get(1));

                String num = bindCardsList.getBankNo();//银行卡号
                if (num.length() > 4) {
                    String s = num.substring(num.length() - 4, num.length());//后四位
                    String ss = num.substring(0, num.length() - 4);//后四位
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < ss.length(); i++) {
                        sb.append("*");
                    }
                    item_zhanghu_safetynum.setText(sb + s);
                } else {
                    item_zhanghu_safetynum.setText(bindCardsList.getBankNo());
                }

            }
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected void onInit() {
        setStatusBarHeight(v_statusbar);
        cb_zhifubao.setBackgroundResource(R.drawable.select);
        cb_weixin.setBackgroundResource(R.drawable.unselect);
        cb_yinhangka.setBackgroundResource(R.drawable.unselect);
        choose_safetycard.setVisibility(View.GONE);
        safety_selectBtn.setBackgroundResource(R.drawable.unselect);
        add_shap_title_tv.setText("账户充值");
        yzmdialog = new WriteYanZhengMaDialog(this);
        userPresenter = new UserPresenter(this);
        InputFilter[] filter = {new CashierInputFilter()};
        //	chongzhi_money.setFilters(filter);// 设置输入位金额

        showExtraDialog();

    }

    @Override
    protected void onReadIntent(Bundle bundle) {
        // TODO Auto-generated method stub

    }

    /**
     * 充值成功Dialog
     */
    private void showExtraDialog() {
        dialog = new Dialog(ActivityChongZhi.this, R.style.rel_dialog);
        View view = LayoutInflater.from(ActivityChongZhi.this).inflate(
                R.layout.user_dialog, null);
        dialog.setContentView(view);
        LinearLayout dialog_ok = (LinearLayout) view
                .findViewById(R.id.dialog_ok);
        TextView dialog_text = (TextView) view.findViewById(R.id.dialog_text);
        dialog_text.setText("充值成功!  请到钱包余额查看!");
        dialog.setCanceledOnTouchOutside(false);
        dialog_ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                dialog.dismiss();
            }
        });
        WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        Display display = wm.getDefaultDisplay();
        // 屏幕宽度
        int screenWidth = display.getWidth();
        // 屏幕高度
        int screenHeight = display.getHeight();
        Window window = dialog.getWindow();

        WindowManager.LayoutParams lp = window.getAttributes();
        window.setGravity(Gravity.CENTER);
        lp.width = screenWidth * 3 / 4;
        lp.height = LayoutParams.WRAP_CONTENT;
        window.setAttributes(lp);

    }

    WriteYanZhengMaDialog yzmdialog;

    @SuppressLint("NewApi")
    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == UserPresenter.payHouse_success) {
                PayInfo payInfo = (PayInfo) entity.getData();
                if (isZFB) {
                    zfb(payInfo);
                } else if (yhk) {
                    yzmdialog.show(getFragmentManager(), "");
                    yzmdialog.setCancelable(false);
                    userPresenter.rongfengPay(uid, payInfo.getCode(), bankId);
                }else if(xiaotong){
                    Intent intent=new Intent(this, WebActivity.class);
                    ///ulinkpay/pay/pay_code/(支付号)/pay_nper/(分期期数)
                    System.out.println("小通地址"+NetPublicConstant.URL+"/ulinkpay/pay/pay_code/"+payInfo.getCode()+"/pay_nper/3");
                    intent.putExtra("url", NetPublicConstant.URL+"/ulinkpay/pay/pay_code/"+payInfo.getCode()+"/pay_nper/3");
                    startActivity(intent);
                }else if (safety){
                    userPresenter.safety(uid, payInfo.getCode(), bankId);// 平安支付
                }
            }
            if (entity.getEventType() == UserPresenter.payHouse_fail) {
                ByAlert.alert(entity.getData().toString());
            }
            if (entity.getEventType() == UserPresenter.yzyue_success) {
                DecimalFormat df = new DecimalFormat("#.00");// 保留两位小数
                BigDecimal bg = new BigDecimal(Double.parseDouble(money) * 100);
                String innermoney = df.format(bg);
                if (isZFB == true) {
                    userPresenter.payHouse(uid, "recharge", "", "6325", "", innermoney, "0");
                } else if (wx) {
                    ByAlert.alert("待开发中");
                } else if (yhk) {
                    userPresenter.payHouse(uid, "recharge", "", "6327", "", innermoney, "0");
                }else if (xiaotong) {
                    userPresenter.payHouse(uid, "recharge", "", "6428", "", innermoney, "0");
                }
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.yzyue_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.rongfeng_success) {
                rongFengBean = (RongFengsBean) entity.getData();
                order_no = rongFengBean.getOrder_no();
            }
            if (entity.getEventType() == UserPresenter.rongfeng_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.yzrf_success) {
                ByAlert.alert(entity.getData());
                finish();
            }
            if (entity.getEventType() == UserPresenter.yzrf_fail) {
                ByAlert.alert(entity.getData());
            }
            if (entity.getEventType() == UserPresenter.safetyPay_success){
                ByAlert.alert(entity.getMsg());
                finish();
            }else if (entity.getEventType() == UserPresenter.safetyPay_fail){
                ByAlert.alert(entity.getMsg());
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
        }
    }


    private String code;

    @Override
    public void getEditText(String edit) {
        // TODO Auto-generated method stub
        if (edit != null) {
            code = edit;
            showProgressDialog("请稍后", true);
            userPresenter.sendRf(order_no, code);
        }
    }

    @Override
    public void cancel() {
        // TODO Auto-generated method stub
        dialog.dismiss();
    }

    private static final int SDK_PAY_FLAG = 1;

    /**
     * 支付宝
     */
    private void zfb(PayInfo bean) {
        /**
         * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
         * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
         * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
         * orderInfo的获取必须来自服务端；
         */
        String money = bean.getTotalPrice();
        double m = Double.parseDouble(money) / 100;
        String content = bean.getName();
        String code = bean.getCode();
        Map<String, String> params = OrderInfoUtil2_0.buildOrderParamMap(SPContants.APPID, m + "", content, code, TimeFormat.getSimData());
        String orderParam = OrderInfoUtil2_0.buildOrderParam(params);
        String sign = OrderInfoUtil2_0.getSign(params, SPContants.RSA_PRIVATE);
        final String orderInfo = orderParam + "&" + sign;
        Runnable payRunnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(ActivityChongZhi.this);
                Map<String, String> result = alipay.payV2(orderInfo, true);

                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };

        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {

                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(ActivityChongZhi.this, "支付成功", Toast.LENGTH_SHORT).show();
                        finish();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(ActivityChongZhi.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }

        ;
    };

}
